import anydbm
import time

class Persist:
    '''As a decorator for all the methods of manipulating data storage, this 
    method opens file before we manipulate data, and closes file after finish
    manipulating data.
    '''
    
    # The file name of the data storage.
    filename = 'javavatask.dbm'
    
    def __init__(self, func):
        self.func = func
    
    def __call__(self, *args):
        # Open the file for read and write.
        file = anydbm.open(self.filename, 'c')
        
        args = (file,) + args[1:]
        result = self.func(*args)
        
        # Close the file
        file.close()
        # Return the result
        return result

key_unfinished = '00000000'
# Today's string, the format likes this: '20080804'
key_today = time.strftime('%Y%m%d')
key_language = 'language'

@Persist
def getLanguage(file):
    if key_language in file.keys():
        return file[key_language]
    else:
        return ''

@Persist
def setLanguage(file, language):
    file[key_language] = language

@Persist
def saveTasks(file, unfinishedTasks, finishedTasks):
    '''Save tasks to file. We use the date strings as the keys of top level, 
    please note that the '00000000' is a special key, the tasks pointed by 
    this key are all tasks of in progress. The real date string keys will 
    point to the finished tasks according to every day. And the main user 
    interface will show both tasks of in progress and finished tasks of 
    the current day. 
    '''
    
    file[key_unfinished] = unfinishedTasks;
    file[key_today] = finishedTasks

@Persist
def loadTasks(file=None):
    '''Load tasks from file, default it just loads tasks for current day.
    '''
    
    unfinishedTasks = ''
    if key_unfinished in file.keys():
       unfinishedTasks = file[key_unfinished]
       
    finishedTasks = ''
    if key_today in file.keys():
       finishedTasks = file[key_today]

    return (unfinishedTasks, finishedTasks)

if __name__ == '__main__':
    print key_today
    saveTasks(None, "", "")
    print loadTasks()